package com.asseco.mio.codex.controllers;

import org.apache.commons.lang.StringUtils;
import org.appfuse.service.GenericManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

import com.asseco.mio.codex.Country;
import com.asseco.mio.core.model.AuditLog;
import com.asseco.mio.core.webapp.controller.BaseFormController;
import java.util.Date;
import org.appfuse.Constants;
import org.springframework.validation.Validator;

@Controller
@RequestMapping("/countryform*")
public class CountryFormController extends BaseFormController {

    private GenericManager<Country, String> countryManager;
    private GenericManager<AuditLog, String> auditLoggerManager = null;

    @Autowired(required = false)
    Validator validator;

    @Autowired
    public void setCountryManager(@Qualifier("countryManager") GenericManager<Country, String> countryManager) {
        this.countryManager = countryManager;
    }

    @Autowired
    public void setAuditLoggerManager(GenericManager<AuditLog, String> auditLoggerManager) {
        this.auditLoggerManager = auditLoggerManager;
    }

    public CountryFormController() {
        setCancelView("redirect:countries");
        setSuccessView("redirect:countries");
    }

    @ModelAttribute
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    protected Country showForm(HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        String userString = request.getRemoteUser();
        try {
            if (!request.isUserInRole(Constants.ADMIN_ROLE)) {
                throw new Exception("");
            }

        } catch (Exception e) {

            response.sendRedirect("/MIO/mainMenu");
        }

        String id = request.getParameter("id");

        if (!StringUtils.isBlank(id)) {
            auditLoggerManager.save(new AuditLog(request.getRemoteUser(), "countryform", "country.delete", countryManager.get(id).getName(),
                    "", request.getRemoteHost(), new Date()));
            return countryManager.get(id);
        }


        return new Country();
    }

    @RequestMapping(method = RequestMethod.POST)
    public String onSubmit(Country country, BindingResult errors, HttpServletRequest request,
            HttpServletResponse response)
            throws Exception {
        if (request.getParameter("cancel") != null) {
            return getCancelView();
        }

        if (validator != null) { // validator is null during testing
            validator.validate(country, errors);

            if (errors.hasErrors() && request.getParameter("delete") == null) { // don't validate when deleting
                return "countryform";
            }
        }
        log.debug("entering 'onSubmit' method...");

        boolean isNew = (country.getId() == null);
        String success = getSuccessView();
        Locale locale = request.getLocale();

        if (request.getParameter("delete") != null) {
            auditLoggerManager.save(new AuditLog(request.getRemoteUser(), "countryform", "country.delete", country.getName(),
                    "", request.getRemoteHost(), new Date()));
            countryManager.remove(country.getId());

            saveMessage(request, getText("country.deleted", locale));


        } else {
            countryManager.save(country);
            String key = (isNew) ? "country.added" : "country.updated";
            saveMessage(request, getText(key, locale));
            auditLoggerManager.save(new AuditLog(request.getRemoteUser(), "countryform", key, country.getName(),
                    "", request.getRemoteHost(), new Date()));

            if (!isNew) {
                success = "redirect:countryform?id=" + country.getId();
            }
        }

        return success;
    }
}
